package com.dm.manage.exception;

import com.dm.manage.common.Result;
import com.dm.manage.common.ResultCode;
import com.dm.manage.common.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理参数验证异常（@Validated）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.warn("参数验证失败: {}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        return getBindingResultResult(bindingResult);
    }
    
    /**
     * 处理参数验证异常（@Valid）
     */
    @ExceptionHandler(BindException.class)
    public Result<Object> handleBindException(BindException e) {
        log.warn("参数绑定失败: {}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        return getBindingResultResult(bindingResult);
    }
    
    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Object> handleBusinessException(BusinessException e) {
        log.warn("业务异常: {}", e.getMessage());
        return ResultUtil.fail(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e) {
        log.error("系统异常: ", e);
        return ResultUtil.fail(ResultCode.INTERNAL_SERVER_ERROR);
    }
    
    /**
     * 处理参数绑定错误
     */
    private Result<Object> getBindingResultResult(BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder errorMessage = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            errorMessage.append(fieldError.getDefaultMessage()).append(";");
        }
        
        if (errorMessage.length() > 0) {
            errorMessage.deleteCharAt(errorMessage.length() - 1);
        }
        
        return ResultUtil.fail(ResultCode.VALIDATE_FAILED.getCode(), errorMessage.toString());
    }
}